package com.yty.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yty.system.entity.AccountInfo;
import com.yty.system.entity.Dept;
import com.yty.system.service.IDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author
 * @since 2023-09-10
 */
@RestController
@RequestMapping("/dept")
public class DeptController {

    @Autowired
    private IDeptService deptService;

    @GetMapping(value = "/tree")
    public Object tree(){
        // 1 查询所有的部门
        List<Dept> list = deptService.list();
        // 2 查询最顶级部门
        Dept dept = deptService.getById(100);
        Dept trees = getTrees(dept, list);
        return trees;
    }

    /**
     * 递归遍历查询数
     * @param node
     * @param list
     * @return
     */
    public Dept getTrees(Dept node, List<Dept> list) {
        String value = node.getId();
        List<Dept> childs = null;
        Iterator<Dept> iterator = list.iterator();
        while (iterator.hasNext()) {
            Dept d = iterator.next();
            if(d.getPId().equals(value)){
                childs = node.getChildren();
                if(childs == null) {
                    childs = new ArrayList<>();
                }
                childs.add(d);
                iterator.remove();
                node.setChildren(childs);
            }
        }
        if(childs != null && !childs.isEmpty()){
            Iterator<Dept> iterator2 = childs.iterator();
            while(iterator2.hasNext()){
                Dept next = iterator2.next();
                getTrees(next,list);
            }
        }
        return node;
    }
//    public Dept getTrees(Dept node, List<Dept> list) {
//        String value = node.getId();
//        List<Dept> childs = null;
//        Iterator<Dept> iterator = list.iterator();
//        while (iterator.hasNext()) {
//            Dept d = iterator.next();
//            if(d.getPId().equals(value)){
//                childs = node.getChildren();
//                if(childs == null) {
//                    childs = new ArrayList<>();
//                }
//                childs.add(d);
//                iterator.remove();
//                node.setChildren(childs);
//            }
//        }
//        if(childs != null && !childs.isEmpty()){
//            Iterator<Dept> iterator2 = childs.iterator();
//            while(iterator2.hasNext()){
//                Dept next = iterator2.next();
//                getTrees(next,list);
//            }
//        }
//        return node;
//    }
}
